package com.dal.oauth.config;

import com.dal.oauth.pojo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import javax.annotation.Resource;
import java.util.LinkedHashMap;

/**
 * 配置授权服务器
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Resource
    private UserDetailsServiceImpl userService;

    @Resource
    private RedisTokenStore redisTokenStore;

    /**
     * 管理器
     */
    @Resource
    private AuthenticationManager authenticationManager;


    /**
     * 客户端配置类
     */
    @Resource
    //private ClientOauth2DataConfiguration oauth2DataConfiguration;

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//        clients.inMemory().withClient(oauth2DataConfiguration.getClientId())
//                .secret(passwordEncoder.encode(oauth2DataConfiguration.getSecret()))
//                .authorizedGrantTypes(oauth2DataConfiguration.getGrantTypes()) // token 授权类型
//                .accessTokenValiditySeconds(oauth2DataConfiguration.getTokenValidityTime()) // token 过期时间
//                .refreshTokenValiditySeconds(oauth2DataConfiguration.getRefreshTokenValidityTime()) // token 刷新过期时间
//                .scopes(oauth2DataConfiguration.getScopes());

        clients.inMemory()
                //配置client_id
                .withClient("appId")
                //配置client-secret
                .secret(passwordEncoder.encode("123456"))
                //配置grant_type，表示授权类型
                .authorizedGrantTypes("refresh_token","password")
                //配置访问token的有效期
                .accessTokenValiditySeconds(3600)
                //配置刷新token的有效期
                .refreshTokenValiditySeconds(864000)
                //配置redirect_uri，用于授权成功后跳转
                .redirectUris("http://www.baidu.com")
                //配置申请的权限范围
                .scopes("all","api");
                //配置grant_type，表示授权类型
                //.authorizedGrantTypes("refresh_token","authorization_code");
    }


    /**
     * 配置令牌端点的安全约束
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 允许访问 token 的公钥，默认 /oauth/token_key 受保护的
        security.tokenKeyAccess("permitAll()")
                // 允许访问 token 的状态，默认 /oauth/check_token 受保护的
                .checkTokenAccess("permitAll()");
    }


    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // 认证器
        endpoints.authenticationManager(authenticationManager)
                // 具体登陆方法
                .userDetailsService(userService)
                // token 存储方式 redis
                .tokenStore(redisTokenStore);
                // 令牌增强对象 ， 增强返回的结果
//                .tokenEnhancer((accessToken, authentication) ->{
//                    // 获取用户信息，然后设置
//                    LoginUser loginUser = (LoginUser) authentication.getPrincipal();
//                    LinkedHashMap<String, Object> map = new LinkedHashMap<>();
//                    map.put("userId",loginUser.getId());
//                    map.put("userName",loginUser.getUsername());
//                    map.put("avatar", loginUser.getAvatar());
//                    DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) accessToken;
//                    token.setAdditionalInformation(map);
//                    return token;
//                });

    }


}